<?php
Yii::import('ext.image.Image');
class NImage
{	
	/**
	 * This function make a SQUARE image by 
	 * RESIZING & CROPPING $source image to $size x $size, then save to $destination
	 * $source & $destination MUST include path
	 *
	 * @param string $source 
	 * @param string $destination 
	 * @param string $size
	 * @return boolean new image saved successful or not
	 * @author QuangNghia
	 */
	public static function resizeAndCrop($source, $destination, $size)
	{
		$image = new Image($source);
		if($image->width < $image->height) {
			$image->resize($size, NULL, Image::WIDTH)->crop($size, $size);
		} else {
			$image->resize(NULL, $size, Image::HEIGHT)->crop($size, $size);
		}
		return $image->save($destination);
	}
	
	/** 
	 * This function make a RECTANGLE image by 
	 * RESIZING & CROPPING $source image to $width x $height, then save to $destination
	 * $source & $destination MUST include path
	 *
	 * @param string $source 
	 * @param string $destination 
	 * @param string $width
	 * @param string $height
	 * @return boolean new image saved successful or not
	 * @author QuangNghia
	 */
	public static function resizeAndCropRect($source, $destination, $width, $height)
	{
		$image = new Image($source);
		$ratio = $width / $height;
		$imageRatio = $image->width / $image->height;
		if($ratio >= $imageRatio) {
			$image->resize($width, NULL, Image::WIDTH)->crop($width, $height);
		} else {
			$image->resize(NULL, $height, Image::HEIGHT)->crop($width, $height);
		}
		return $image->save($destination);
	}

	/**
	 * Resize $source file to $width and $height, maintain aspect ratio
	 * and save to $destination
	 *
	 * @param string $source 
	 * @param string $destination 
	 * @param string $width 
	 * @param string $height 
	 * @return void
	 * @author QuangNghia
	 */
	public static function resize($source, $destination, $width, $height, $ratio=Image::AUTO)
	{
		$image = new Image($source);
		$image->resize($width,$height, $ratio);
		return $image->save($destination);
	}
}

